//
//  ViewController.m
//  EWSClient
//
//  Created by Suraeva Yana on 21.11.12.
//  Copyright (c) 2012 Сураева Яна. All rights reserved.
//

#import "ViewController.h"
#import "RequestHandler.h"
#import "FoldersViewController.h"
#import "SendQueryToDB.h"
#import "SQLQueries.h"


@interface ViewController (){
    IBOutlet UITextField *passwordField;
    IBOutlet UITextField *loginField;
    IBOutlet UIButton *enterButton;
    IBOutlet UIButton *exitButton;
}
- (NSString *)dataFilePath:(NSString *)name;
- (NSData *)dataWithBase64EncodedString:(NSString *)string;

@end

@implementation ViewController
@synthesize folderID;


- (void) viewWillAppear:(BOOL)animated {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults boolForKey:@"logged"]) {
        enterButton.titleLabel.text = @"Mails";
        loginField.text = [defaults stringForKey:@"login"];
        passwordField.text = [defaults stringForKey:@"password"];
        exitButton.hidden = NO;
    }
    else {
        enterButton.titleLabel.text = @"Sign In";
        loginField.text = @"";
        passwordField.text = @"";
        exitButton.hidden = YES;
        
    }
}

- (void)viewDidLoad
{
    self.title = @"Authorization";
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults boolForKey:@"logged"]) {
        FoldersViewController *foldersViewController = [[FoldersViewController alloc] initWithNibName:@"FoldersViewController" bundle:nil];
//        foldersViewController.requestHandlerInstance=requestInstance;
        [self.navigationController pushViewController:foldersViewController animated:YES];
        [foldersViewController release];
    }
    [super viewDidLoad];
   
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}



- (void)dealloc {
    [loginField release];
    [passwordField release];
    [super dealloc];
}

- (IBAction)exitButton:(id)sender{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:NO forKey:@"logged"];
    [defaults setObject:@"" forKey:@"login"];
    [defaults setObject:@"" forKey:@"password"];
    [defaults synchronize];
    [self viewWillAppear:YES];
}

- (IBAction)enterButton:(id)sender {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults boolForKey:@"logged"]) {
        
        FoldersViewController *foldersViewController = [[FoldersViewController alloc] initWithNibName:@"FoldersViewController" bundle:nil];
        [self.navigationController pushViewController:foldersViewController animated:YES];
        [foldersViewController release];
    } else {
        [defaults setObject:loginField.text forKey:@"login"];
        [defaults setObject:passwordField.text forKey:@"password"];
        [defaults synchronize];
        
        RequestHandler *requestInstance = [[RequestHandler alloc] initWithServerURL:[NSURL URLWithString:@"https://mail.digdes.com/ews/exchange.asmx"] withUsername:[defaults stringForKey:@"login"] withPassword:[defaults stringForKey:@"password"]];
        
        [defaults setBool:[requestInstance testUserCredential] forKey:@"logged"];
        [defaults synchronize];
        NSLog(@"%d",[defaults boolForKey:@"logged"]);
        if ([defaults boolForKey:@"logged"]) {
            
            /*NSDictionary *temp = [requestInstance getAttachmentWithID:@"AAANAHMyQGRpZ2Rlcy5jb20ARgAAAAAAIVkFkxwE/U6oKVqAurvPrwcAXtbn1WidSku/aYPp03dwPAAAAAsdMwAAXtbn1WidSku/aYPp03dwPAAAERzX0gAAAQYABAAFAAAA"];
            if ([[temp valueForKey:@"Name"] hasSuffix:@".pdf"]) {
                
                NSData* data = [self dataWithBase64EncodedString:[temp valueForKey:@"Content"]];
                NSString *path = [self dataFilePath:[temp valueForKey:@"Name"]];
                [data writeToFile:path atomically:YES];
                NSLog(@"%@",path);
                
            }*/
            
                        
            
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory=[paths objectAtIndex:0];
            NSString *path= [documentsDirectory stringByAppendingPathComponent:@"FoldersForMail"];
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSError *error;
            BOOL success = [fileManager fileExistsAtPath:path];
            if(!success) {
                NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"FoldersForMail"];
                success = [fileManager copyItemAtPath:defaultDBPath toPath:path error:&error];
                
                if (!success)
                    NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);}
            
            
            [SendQueryToDB insertOrDeleteQuery:[SQLQueries deleteAllFolders]];
            [SendQueryToDB insertOrDeleteQuery:[SQLQueries deleteAllMails]];
            [requestInstance syncFolderHierarchyUsingSyncState:nil];

            FoldersViewController *foldersViewController = [[FoldersViewController alloc] initWithNibName:@"FoldersViewController" bundle:nil];
//            [foldersViewController initData];
            foldersViewController.requestHandlerInstance=requestInstance;
            [self.navigationController pushViewController:foldersViewController animated:YES];
            [foldersViewController release];
        }
        
    }

}

- (NSString *)dataFilePath:(NSString *)name {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentsPath = [documentsDirectory
                               stringByAppendingPathComponent:name];
    return documentsPath;
    
}

- (NSData *)dataWithBase64EncodedString:(NSString *)string
{
    const char lookup[] =
    {
        99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
        99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99,
        99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 62, 99, 99, 99, 63,
        52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 99, 99, 99, 99, 99, 99,
        99,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
        15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 99, 99, 99, 99, 99,
        99, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
        41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 99, 99, 99, 99, 99
    };
    
    NSData *inputData = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    long long inputLength = [inputData length];
    const unsigned char *inputBytes = [inputData bytes];
    
    long long maxOutputLength = (inputLength / 4 + 1) * 3;
    NSMutableData *outputData = [NSMutableData dataWithLength:maxOutputLength];
    unsigned char *outputBytes = (unsigned char *)[outputData mutableBytes];
    
    int accumulator = 0;
    long long outputLength = 0;
    unsigned char accumulated[] = {0, 0, 0, 0};
    for (long long i = 0; i < inputLength; i++)
    {
        unsigned char decoded = lookup[inputBytes[i] & 0x7F];
        if (decoded != 99)
        {
            accumulated[accumulator] = decoded;
            if (accumulator == 3)
            {
                outputBytes[outputLength++] = (accumulated[0] << 2) | (accumulated[1] >> 4);
                outputBytes[outputLength++] = (accumulated[1] << 4) | (accumulated[2] >> 2);
                outputBytes[outputLength++] = (accumulated[2] << 6) | accumulated[3];
            }
            accumulator = (accumulator + 1) % 4;
        }
    }
    
    //handle left-over data
    if (accumulator > 0) outputBytes[outputLength] = (accumulated[0] << 2) | (accumulated[1] >> 4);
    if (accumulator > 1) outputBytes[++outputLength] = (accumulated[1] << 4) | (accumulated[2] >> 2);
    if (accumulator > 2) outputLength++;
    
    //truncate data to match actual output length
    outputData.length = outputLength;
    return outputLength? outputData: nil;
}


@end
